package com.cars.util.http;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 传输通道
 * 参数 需要传输的报文
 * @return 可以用于传输的报文
 * @author zhaoyp 
 * @date 2013-11-13
 */

public class MsgChannel {
    

    static Logger log = null;
    
	/**
     * 打包数据(包括压缩,加密,转16进制)
     * @param xmlInfo 明文报文
     * @return 处理后的报文
     * @author zhaoyp
     * @date 2013-11-06
     */
	public static String sendMsg(String xmlInfo)throws Exception{
		
		
		//打印日志
		log =  LoggerFactory.getLogger("operationLogAppender");
		//定义最终处理结果		
		String hexMsgStr ="";
        
		//转换成字节形式gb2312格式
		byte[] byteMsg = xmlInfo.getBytes(Constants.CHANNEL_ENCODE);

		//log.info("压缩前的字节数为:"+byteMsg.length);
		//压缩
		byte[] comMsg = CompAndDecompressUtil.compress(byteMsg);
		
		//log.info("压缩后的字节数为:"+comMsg.length);
		//将压缩后的字节码转换成明文字符串,
		//此处必须为ISO-8859-1，否则会有字节长度发生变化问题
		String tmpMsg = new String(comMsg,"ISO-8859-1");
		//判断字节数的长度能否被8整除,
		//因为传入DES压缩和解压缩方法里的字节数必须是8的倍数,不足的要补成8的倍数
		int len = comMsg.length;
		if(len % 8 != 0){
			//求余
			int reNum = len % 8;
			//计算需要补几个结束符\0
			int tmpNum = 8 - reNum;
			StringBuffer newXml = new StringBuffer(tmpMsg);
			for(int i = 0;i <tmpNum;i++){
				 newXml.append(" ");
			}
			String newMsg = new String(newXml);
			byte[] newMsgByte = newMsg.getBytes("ISO-8859-1");
			String keyStr= Constants.CHANNEL_PASSWORD;
			byte[] keyByte = keyStr.getBytes(Constants.CHANNEL_ENCODE);
			
			//加密
			
			byte[] encByte = EncAndDecryptionUtil.encrypt(newMsgByte, keyByte);

			//log.info("加密后的字节数为:"+encByte.length);
			
					
			//转换成16进制型的字符串  
			String hexMsgTmp = bytesToHexString(encByte);
			
			//截取掉后面的16位
			hexMsgStr = hexMsgTmp.substring(0,hexMsgTmp.length()-16);
		
				
		}else{
			String keyStr= Constants.CHANNEL_PASSWORD;
			byte[] keyByte = keyStr.getBytes(Constants.CHANNEL_ENCODE);
			
			//加密
			
			byte[] encByte = EncAndDecryptionUtil.encrypt(comMsg, keyByte);
			//log.info("加密后的字节数为:"+encByte.length);
			
			

			//转换成16进制型的字符串  
			String hexMsgTmp = bytesToHexString(encByte);
			
			//截取掉后面的16位
			hexMsgStr = hexMsgTmp.substring(0,hexMsgTmp.length()-16);
		
		}
			
		log.info("压缩加密成功！字节数为:"+hexMsgStr.length());
		return hexMsgStr;
	}

    /**
     * 解包(包括解压,解密,进行16进制反转)
     * @param xmlInfo
     * @return 明文报文
     * @throws IOException
     * @author zhaoyp
     * @date 2013-11-06
     */
	public static String recMsg(String xmlInfo) throws Exception{
			
	  	    //打印日志
	  	    log =  LoggerFactory.getLogger("operationLogAppender");
		  	StringBuffer sb = new StringBuffer(xmlInfo);
		  	//java实现DES加密解密将字节数组转换成16进制字符串时固定多出来的字符串
		  	sb.append("FEB959B7D4642FCB");
		  	String xml = new String(sb);
		  	//转换成字节编码格式
		  	byte[] byteMsg = hexStringToBytes(xml);
		  	
		  	//解密
		  	String keyStr= Constants.CHANNEL_PASSWORD;
		  	byte[] keyByte = keyStr.getBytes(Constants.CHANNEL_ENCODE);	
		  	byte[] decByte = EncAndDecryptionUtil.decrypt(byteMsg, keyByte);
		  	
		  	//解压缩
		  	byte[] decomByte = CompAndDecompressUtil.decompress(decByte);
		  	
		  	
		  	//还原成明码报文
		  	String xmlInfoRecTmp = new String(decomByte,Constants.CHANNEL_ENCODE);
		  	//获取</Info>的索引
		  	int index = xmlInfoRecTmp.indexOf("</Info>");
		  	//截取报文信息
		  	String xmlInfoRec = xmlInfoRecTmp.substring(0, index + 7);

			//log.info(xmlInfoRec);
		  	return xmlInfoRec;
	  		
	}
	
	/**
     * 十六进制字符串转换成明文字符串
     * @param hex String 十六进制
     * @return String 转换后的字符串
     * @author zhaoyp
     * @date 2013-11-06
     */
	public static String hex2bin(String hex) throws Exception{

        String digital = "0123456789ABCDEF";
        char[] hex2char = hex.toCharArray();
        byte[] bytes = new byte[hex.length() / 2];
        int temp;
        for (int i = 0; i < bytes.length; i++) {
            temp = digital.indexOf(hex2char[2 * i]) * 16;
            temp += digital.indexOf(hex2char[2 * i + 1]);
            bytes[i] = (byte) (temp & 0xff);
        }
        return new String(bytes,"gb2312");

    }
	/**
     * 字符串转换成十六进制值gb2312格式
     * @param bin String 我们看到的要转换成十六进制的字符串
     * @return 
     * @author zhaoyp
     * @date 2013-11-06
     */
    public static String bin2hex(String bin) throws Exception{

        char[] digital = "0123456789ABCDEF".toCharArray();
        StringBuffer sb = new StringBuffer("");
        byte[] bs = bin.getBytes("gb2312");
        int bit;

        for (int i = 0; i < bs.length; i++) {

            bit = (bs[i] & 0x0f0) >> 4;

            sb.append(digital[bit]);
            bit = bs[i] & 0x0f;
            sb.append(digital[bit]);
        }

        return sb.toString();

    }
    /** 
     * 将16进制字符串转换成字节码 
     * @param hexString  
     * @return byte[]
     * @author zhaoyp
     * @date 2013-11-06 
     */  
     public static byte[] hexStringToBytes(String hexString) {  
         if (hexString == null || hexString.equals("")) {  
             return null;  
         }  
         hexString = hexString.toUpperCase();  
         int length = hexString.length() / 2;  
         char[] hexChars = hexString.toCharArray();  
         byte[] d = new byte[length];  
         for (int i = 0; i < length; i++) {  
             int pos = i * 2;  
             d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));  
         }  
         return d;  
     }
     /** 
      * 将字符转换成字节形式 
      * @param c char 
      * @return byte
      * @author zhaoyp
      * @date 2013-11-06 
      */  
      public static byte charToByte(char c) {  
          return (byte) "0123456789ABCDEF".indexOf(c);  
      }
      /** 
       * 将java字节码转成16进制型的字符串 (速度比byte2hex()方法快很多)
       * @param src
       * @return
       * @author zhaoyp
       * @date 2013-11-06 
       */
      public static String bytesToHexString(byte[] src){  
	      StringBuilder stringBuilder = new StringBuilder("");  
	    if (src == null || src.length <= 0) {  
	          return null;  
	      }  
	      for (int i = 0; i < src.length; i++) {  
	          int v = src[i] & 0xFF;  
	         String hv = Integer.toHexString(v);  
	         if (hv.length() < 2) {  
	             stringBuilder.append(0);  
	        }  
	          stringBuilder.append(hv);  
	    }  
	      return stringBuilder.toString();  
	  }  
      /*
      public static String byte2hex(byte[] b) { 

          // 转成16进制字符串
          String hs = "";
          String tmp = "";
          for (int n = 0; n < b.length; n++) {

              //整数转成十六进制表示
              tmp = (Integer.toHexString(b[n] & 0xFF));
              if (tmp.length() == 1) {
                  hs = hs + "0" + tmp;

              } else {
                  hs = hs + tmp;
              }
          }

          tmp = null;
          return hs.toUpperCase(); //转成大写

      }*/
      
      
     
	  public static void main(String[] args)throws Exception{	
		
	  }
	  
	  
	 


}




